<template>
  <div class="system-message-list">
    <!-- 头部操作栏 -->
    <div class="message-header">
      <div class="header-left">
        <h3>系统消息</h3>
        <el-tag v-if="unreadCount > 0" type="danger" size="small">
          {{ unreadCount }}条未读
        </el-tag>
      </div>
      <div class="header-right">
        <el-button 
          v-if="selectedMessages.length > 0" 
          type="primary" 
          size="small"
          @click="markSelectedAsRead"
          :loading="markingRead"
        >
          标记已读
        </el-button>
        <el-button 
          v-if="unreadCount > 0" 
          type="success" 
          size="small"
          @click="markAllAsRead"
          :loading="markingAllRead"
        >
          全部已读
        </el-button>
        <el-button 
          size="small"
          @click="refreshMessages"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="message-content" v-loading="loading">
      <div v-if="messages.length === 0" class="empty-state">
        <el-empty description="暂无系统消息" />
      </div>
      
      <div v-else class="message-items">
        <div 
          v-for="message in messages" 
          :key="message.id"
          :class="['message-item', { 'unread': !message.isRead, 'selected': selectedMessages.includes(message.id) }]"
          @click="toggleSelect(message.id)"
        >
          <div class="message-checkbox">
            <el-checkbox 
              :model-value="selectedMessages.includes(message.id)"
              @change="toggleSelect(message.id)"
            />
          </div>
          
          <div class="message-icon">
            <el-icon :size="24" :color="getMessageTypeColor(message.type)">
              <component :is="getMessageTypeIcon(message.type)" />
            </el-icon>
          </div>
          
          <div class="message-body">
            <div class="message-title">{{ message.title }}</div>
            <div class="message-summary">{{ message.content }}</div>
            <div class="message-meta">
              <span class="message-time">{{ formatTime(message.createTime) }}</span>
              <el-tag :type="getMessageTypeTagType(message.type)" size="small">
                {{ getMessageTypeName(message.type) }}
              </el-tag>
            </div>
          </div>
          
          <div class="message-actions">
            <el-button 
              v-if="!message.isRead" 
              type="primary" 
              size="small" 
              text
              @click.stop="markAsRead(message.id)"
            >
              标记已读
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              text
              @click.stop="deleteMessage(message.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="message-pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Bell, 
  Warning, 
  InfoFilled, 
  SuccessFilled, 
  CircleCheck,
  Document,
  House,
  User
} from '@element-plus/icons-vue'
import { 
  getSystemMessages, 
  markSystemMessageRead, 
  markSystemMessagesRead,
  deleteSystemMessage,
  getSystemUnreadCount 
} from '@/utils/apiService'

// 响应式数据
const loading = ref(false)
const markingRead = ref(false)
const markingAllRead = ref(false)
const messages = ref([])
const selectedMessages = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const unreadCount = ref(0)

// 计算属性
const hasUnreadMessages = computed(() => unreadCount.value > 0)

// 方法
const loadMessages = async () => {
  loading.value = true
  try {
    const response = await getSystemMessages({
      page: currentPage.value,
      size: pageSize.value
    })
    
    if (response.code === '200') {
      messages.value = response.data.messages || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载系统消息失败')
    }
  } catch (error) {
    console.error('加载系统消息失败:', error)
    ElMessage.error('加载系统消息失败')
  } finally {
    loading.value = false
  }
}

const loadUnreadCount = async () => {
  try {
    const response = await getSystemUnreadCount()
    if (response.code === '200') {
      unreadCount.value = response.data.unreadCount || 0
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

const refreshMessages = async () => {
  await Promise.all([loadMessages(), loadUnreadCount()])
}

const toggleSelect = (messageId) => {
  const index = selectedMessages.value.indexOf(messageId)
  if (index > -1) {
    selectedMessages.value.splice(index, 1)
  } else {
    selectedMessages.value.push(messageId)
  }
}

const markAsRead = async (messageId) => {
  try {
    const response = await markSystemMessageRead(messageId)
    if (response.code === '200') {
      // 更新本地状态
      const message = messages.value.find(m => m.id === messageId)
      if (message) {
        message.isRead = true
      }
      unreadCount.value = Math.max(0, unreadCount.value - 1)
      ElMessage.success('标记已读成功')
    } else {
      ElMessage.error(response.message || '标记已读失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

const markSelectedAsRead = async () => {
  if (selectedMessages.value.length === 0) return
  
  markingRead.value = true
  try {
    const response = await markSystemMessagesRead(selectedMessages.value)
    if (response.code === '200') {
      // 更新本地状态
      selectedMessages.value.forEach(id => {
        const message = messages.value.find(m => m.id === id)
        if (message && !message.isRead) {
          message.isRead = true
          unreadCount.value = Math.max(0, unreadCount.value - 1)
        }
      })
      selectedMessages.value = []
      ElMessage.success('批量标记已读成功')
    } else {
      ElMessage.error(response.message || '批量标记已读失败')
    }
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  } finally {
    markingRead.value = false
  }
}

const markAllAsRead = async () => {
  const unreadMessageIds = messages.value
    .filter(m => !m.isRead)
    .map(m => m.id)
  
  if (unreadMessageIds.length === 0) return
  
  markingAllRead.value = true
  try {
    const response = await markSystemMessagesRead(unreadMessageIds)
    if (response.code === '200') {
      // 更新本地状态
      messages.value.forEach(message => {
        if (!message.isRead) {
          message.isRead = true
        }
      })
      unreadCount.value = 0
      ElMessage.success('全部标记已读成功')
    } else {
      ElMessage.error(response.message || '全部标记已读失败')
    }
  } catch (error) {
    console.error('全部标记已读失败:', error)
    ElMessage.error('全部标记已读失败')
  } finally {
    markingAllRead.value = false
  }
}

const deleteMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteSystemMessage(messageId)
    if (response.code === '200') {
      // 从列表中移除
      const index = messages.value.findIndex(m => m.id === messageId)
      if (index > -1) {
        const message = messages.value[index]
        if (!message.isRead) {
          unreadCount.value = Math.max(0, unreadCount.value - 1)
        }
        messages.value.splice(index, 1)
        total.value = Math.max(0, total.value - 1)
      }
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadMessages()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadMessages()
}

// 工具方法
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const getMessageTypeIcon = (type) => {
  const iconMap = {
    'system': Bell,
    'warning': Warning,
    'info': InfoFilled,
    'success': SuccessFilled,
    'contract': Document,
    'house': House,
    'user': User
  }
  return iconMap[type] || Bell
}

const getMessageTypeColor = (type) => {
  const colorMap = {
    'system': '#409eff',
    'warning': '#e6a23c',
    'info': '#909399',
    'success': '#67c23a',
    'contract': '#f56c6c',
    'house': '#409eff',
    'user': '#909399'
  }
  return colorMap[type] || '#409eff'
}

const getMessageTypeName = (type) => {
  const nameMap = {
    'system': '系统通知',
    'warning': '警告',
    'info': '信息',
    'success': '成功',
    'contract': '合同',
    'house': '房源',
    'user': '用户'
  }
  return nameMap[type] || '系统通知'
}

const getMessageTypeTagType = (type) => {
  const tagMap = {
    'system': 'primary',
    'warning': 'warning',
    'info': 'info',
    'success': 'success',
    'contract': 'danger',
    'house': 'primary',
    'user': 'info'
  }
  return tagMap[type] || 'primary'
}

// 生命周期
onMounted(() => {
  refreshMessages()
})
</script>

<style scoped>
.system-message-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h3 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 8px;
}

.message-content {
  flex: 1;
  overflow-y: auto;
  background: #f5f7fa;
}

.empty-state {
  padding: 60px 20px;
}

.message-items {
  padding: 16px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.message-item.unread {
  border-left: 4px solid #409eff;
  background: #f0f9ff;
}

.message-item.selected {
  border-color: #409eff;
  background: #f0f9ff;
}

.message-checkbox {
  margin-top: 2px;
}

.message-icon {
  margin-top: 2px;
}

.message-body {
  flex: 1;
  min-width: 0;
}

.message-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.4;
}

.message-summary {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-time {
  color: #909399;
  font-size: 12px;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 2px;
}

.message-pagination {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
}
</style>
